package cool.xinya.ess.controller;

import cool.xinya.ess.common.Result;
import cool.xinya.ess.entity.ElasticEntity;
import cool.xinya.ess.service.BaseElasticService;
import cool.xinya.ess.util.ElasticUtil;
import cool.xinya.ess.util.ResultUtil;
import cool.xinya.ess.vo.ElasticDataVo;
import cool.xinya.ess.vo.QueryVo;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/es")
public class ElasticMgrController {
    @Resource
    private BaseElasticService baseElasticService;

    /**
     * 新增数据
     *
     * @param elasticDataVo 数据
     */
    @PostMapping(value = "/add")
    public Result add(@RequestBody ElasticDataVo elasticDataVo) {
        ElasticEntity elasticEntity = new ElasticEntity();
        elasticEntity.setId(elasticDataVo.getElasticEntity().getId());
        elasticEntity.setData(elasticDataVo.getElasticEntity().getData());
        baseElasticService.insertOrUpdateOne(elasticDataVo.getIdxName(), elasticEntity);
        return ResultUtil.success();
    }

    /**
     * 删除
     */
    @PostMapping(value = "/delete")
    public Result delete(@RequestBody ElasticDataVo elasticDataVo) {
        baseElasticService.deleteOne(elasticDataVo.getIdxName(), elasticDataVo.getElasticEntity());
        return ResultUtil.success();
    }

    /**
     * @param queryVo 查询实体对象
     */
    @GetMapping(value = "/get")
    public Result get(@RequestBody QueryVo queryVo) {
        Class<?> clazz = ElasticUtil.getClazz(queryVo.getClassName());
        Map<String, Object> params = queryVo.getQuery().get("match");
        Set<String> keys = params.keySet();
        MatchQueryBuilder queryBuilders = null;
        for (String ke : keys) {
            queryBuilders = QueryBuilders.matchQuery(ke, params.get(ke));
        }
        SearchSourceBuilder searchSourceBuilder = ElasticUtil.initSearchSourceBuilder(queryBuilders);
        List<?> data = baseElasticService.search(queryVo.getIdxName(), searchSourceBuilder, clazz);
        return ResultUtil.success(data);
    }
}
